package controller;

import java.io.IOException;

import XMLUtilities.PDFUtilities;
import XMLUtilities.XQUtilities;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class DownloadServlet
 */
public class DownloadServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public DownloadServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	@Override
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String item = request.getParameter("item");
		if (item.equals("menu")) {
			int id = Integer.parseInt(request.getParameter("id"));
			String realPath = getServletContext().getRealPath("/");

			String outputXML = XQUtilities.getMenuXML(realPath,
					String.valueOf(id));
			outputXML = "<dishes>" + outputXML + "</dishes>"; // add node root
			System.out.println(outputXML);

			response.setContentType("application/pdf");
			String xslPath = realPath + "style-sheet/planFo.xsl";
			String foPath = realPath + "style-sheet/planFo.fo";

			byte[] content = PDFUtilities.printPDF(outputXML, xslPath, foPath, realPath);
			response.setContentLength(content.length);
			response.getOutputStream().write(content);
			response.getOutputStream().flush();
		} else if (item.equals("recipe")) {
			int recipeId = Integer.parseInt(request.getParameter("recipeId"));
			String realPath = getServletContext().getRealPath("/");
			
			String outputXML = XQUtilities.getRecipeIncludeDish(realPath, recipeId);
			System.out.println(outputXML);
			
			response.setContentType("application/pdf");
			String xslPath = realPath + "style-sheet/recipeFO.xsl";
			String foPath = realPath + "style-sheet/recipeFo.fo";
			
			byte[] content = PDFUtilities.printPDF(outputXML, xslPath, foPath, realPath);
			response.setContentLength(content.length);
			response.getOutputStream().write(content);
			response.getOutputStream().flush();
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	@Override
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}
